<template>
  <div class="incompleteBillingPane">
    <section>
      <el-space wrap>
        <div>
          <span class="fs-base">待收</span>
          <span class="fs-large fc-success ml10">￥{{ amountTotalInfo.incomeTotalMoney }}</span>
        </div>
      </el-space>
      <el-button type="primary" plain class="fl-r" @click="handleReceivables">添加待收账单</el-button>
      <el-button type="danger" plain class="fl-r mr10" :disabled="multipleSelection.length === 0" @click="handleBatchRemove">批量删除</el-button>
    </section>
    <el-table :data="billList" class="mt20" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="费用名称" />
      <el-table-column prop="money" label="金额" />
      <el-table-column prop="billCycleBegin" label="账单开始日期" :width="100" />
      <el-table-column prop="billCycleEnd" label="账单结束日期" :width="100" />
      <el-table-column prop="noticeDate" label="待收日期" :width="100" />
      <el-table-column prop="receiverName" label="操作人" />
      <el-table-column label="操作" :width="120">
        <template #default="scope">
          <el-button link type="primary" @click="handleCollection(scope.row)">收款</el-button>
          <el-button link type="danger" @click="handleRemoveBilling(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      layout="total, prev, pager, next"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览图片 -->
    <el-dialog v-model="previewVisible">
      <img w-full :src="previewImageUrl" />
    </el-dialog>
    <!-- 删除账单弹窗 -->
    <BillRemoveDl :visible="removeBillingVisible" :info="currentBill" @cancel="handleRemoveBillingClose" @ok="handleRemoveBillingOk"></BillRemoveDl>
    <!-- 添加待收账单 -->
    <ReceivablesDl
      :visible="receivablesVisible"
      @cancel="handleReceivablesClose"
      @ok="handleReceivablesOk"
    />
    <el-dialog title="收款" v-model="collectionVisible" width="520px" :fullscreen="mobile" class="dialog-content-clear">
      <el-alert title="提示：付款后账单将显示在完成账单中。" type="warning" :closable="false" />
      <div class="ph-16">
        <div class="primary-section mt20">
          <el-space>
            <el-space>
              <span>费用名称</span>
              <span>{{ currentBill.name }}</span>
            </el-space>
            <el-space>
              <span>账单金额</span>
              <span>+{{ currentBill.money }}元</span>
            </el-space>
            <el-space>
              <span>待收日期</span>
              <span>{{ currentBill.noticeDate }}</span>
            </el-space>
          </el-space>
        </div>
        <el-form :model="collectionForm" ref="collectionFormRef" label-position="top">
          <div class="primary-section mt20">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="collectionForm.remark" type="textarea" :rows="3" show-word-limit :max="150" placeholder="请填写备注信息"></el-input>
            </el-form-item>
          </div>
          <div class="primary-section mt20">
            <el-form-item label="凭证图片" prop="pictureUrlList">
              <el-row>
                <el-col :span="24">
                  <div class="fs-base fc-secondary">限3张，图片大小不超过10M</div>
                </el-col>
                <el-col :span="24">
                  <el-upload
                    v-model:file-list="collectionPictureUrlList"
                    :headers="headers"
                    :action="uploadUrl"
                    list-type="picture-card"
                    :before-upload="collectionPictureBeforeUpload"
                    :on-exceed="handleOnExceed"
                    :on-success="handleUploadOnSuccess"
                    :multiple="true"
                    :auto-upload="false"
                    :limit="3"
                    accept="image/png, image/jpeg"
                    :class="{'is-full': collectionPictureUrlList.length === 3}"
                    ref="picRef"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCollectionClose">取消</el-button>
          <el-button type="danger" @click="handleCollectionOk">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="CompleteBillingPane">
import { Edit, CircleCloseFilled } from '@element-plus/icons-vue'
import useAppStore from '@/store/modules/app'
import ReceivablesDl from '../receivablesDl.vue'
import { parseTime } from '@/utils/ruoyi'
import billApi from '@/api/room/bill';
import { getToken } from '@/utils/auth'
import BillRemoveDl from '@/components/BillRemoveDl/index.vue'

const { proxy } = getCurrentInstance()

const { checkInInfo, updateCheckInInfo } = inject('checkInInfo')
const imageVisible = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const removeBillingVisible = ref(false)
const receivablesVisible = ref(false)
const collectionVisible = ref(false)
const pictureUrlList = ref([])
const total = ref(0)
const loading = ref(false)
const billList = ref([])
const amountTotalInfo = ref({})
const collectionPictureUrlList = ref([])
const currentBill = ref({})
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址
const headers = ref({ authorization: getToken() })
const uploadCount = ref(0)
const collectionUploadedUrl = ref([])
// {
//   name: '房租',
//   money: 102,
//   payTime: '2023-12-31'
// }
const fileList = ref([{
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  }, {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  }])
const multipleSelection = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  remarkForm: {
    remark: undefined
  },
  removeBillingForm: {
    id: undefined,
    buildingName: undefined,
    renterName: undefined,
    payDate: undefined,
    money: undefined
  },
  collectionForm: {
    remark: undefined,
    pictureUrlList: []
  },
})
const { remarkForm, removeBillingForm, queryParams, collectionForm } = toRefs(data)


// 图片上传
function handleImagePreview(uploadFile) {
  previewImageUrl.value = uploadFile.url
  previewVisible.value = true
}
function handleImageRemove(uploadFile, uploadFiles) {
  console.log(uploadFile, uploadFiles)
}

// 删除账单
function handleRemoveBilling(row) {
  currentBill.value = row
  removeBillingVisible.value = true
}
function handleRemoveBillingClose() {
  removeBillingVisible.value = false
}
function handleRemoveBillingOk() {
  billApi.remove(currentBill.value.billId).then(() => {
    proxy.$modal.msgSuccess("账单删除成功");
    removeBillingVisible.value = false
    getList()
  })
}
// 批量删除账单
function handleBatchRemove() {
  proxy.$modal.confirm(`确定删除${multipleSelection.value.length}条账单?`)
    .then(() => {
      let billIds = multipleSelection.value.map(item => item.billId)
      billApi.remove(billIds.join(',')).then(() => {
        proxy.$modal.msgSuccess("账单删除成功");
        removeBillingVisible.value = false
        getList()
      })
    })
    .catch(() => {})
}


// 图片上传 覆盖默认上传行为
function pictureRequestUpload() {}
/** 上传预处理 */
function pictureBeforeUpload(file) {
  console.log(file, pictureUrlList.value)
  if (file.type.indexOf("image/") == -1) {
    proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
    return false
  }
  const isLtSize = file.size / 1024 / 1024 < 2
  if (!isLtSize) {
    proxy.$modal.msgError("请上传小于2MB的图片。")
    return false
  }
  return true
  // if (file.type.indexOf("image/") == -1) {
  //   proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
  // } else {
  //   const reader = new FileReader();
  //   reader.readAsDataURL(file);
  //   reader.onload = () => {
  //     options.img = reader.result;
  //     options.filename = file.name;
  //   };
  // }
}



/* 添加待收账单 */
function handleReceivables() {
  receivablesVisible.value = true
}
function handleReceivablesClose() {
  receivablesVisible.value = false
}

function handleReceivablesOk(rows) {
  let params = rows.map(item => {
    // 主要承租人
    let mainRenter = checkInInfo.value.renterList.find(item => item.mainFlag === '1')
    return {
      ...item,
      checkInId: checkInInfo.value.checkInId,
      roomId: checkInInfo.value.roomId,
      renterId: mainRenter ? mainRenter.renterId : null,
      renterName: mainRenter ? mainRenter.name : null,
      contacts: mainRenter ? mainRenter.contacts : null,
      status: '1', // 账单状态 1待收，2完成，3取消
      belong: '1', // 账单类型（1：租客）
      payPlatForm: '1', // 支付平台（1：线下，2：线上）
      inoutFlag: '1', // 1收入，2支出
    }
  })
  billApi.batchSave(params).then(res => {
    proxy.$modal.msgSuccess("待收账单添加成功");
    getList()
    receivablesVisible.value = false
  })
}

// 收款弹窗
function handleCollection(row) {
  currentBill.value = { ...row }
  collectionVisible.value = true
}
function handleCollectionClose() {
  collectionVisible.value = false
}
function handleCollectionOk() {
  if (collectionPictureUrlList.value.length === 0) {
    return update()
  }
  uploadCount.value = 0
  collectionUploadedUrl.value = []
  proxy.$refs['picRef'].submit()
  
}
// 图片上传 覆盖默认上传行为
function collectionPictureRequestUpload() {}
/** 上传预处理 */
function collectionPictureBeforeUpload(file) {
  if (file.type.indexOf("image/") == -1) {
    proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。")
    return false
  }
  const isLtSize = file.size / 1024 / 1024 < 2
  if (!isLtSize) {
    proxy.$modal.msgError("请上传小于2MB的图片。")
    return false
  }
  return true
}
// 当超出限制时，执行的钩子函数
function handleOnExceed(files) {
  proxy.$modal.msgWarning("最多只能选择三张图片")
}
function handleUploadOnSuccess(res, file) {
  if (res.code === 200) {
    uploadCount.value++
    collectionUploadedUrl.value.push({ name: res.data.name, url: res.data.url})
    if (uploadCount.value === collectionPictureUrlList.value.length) {
      // 图片都上传成功后才调用收款接口
      update()
    }
  } else {
    proxy.$modal.msgError(file.name + '上传失败：' + res.msg)
  }
}
// 收款
function update() {
  let params = {
    ...collectionForm.value,
    billId: currentBill.value.billId,
    picUrl: JSON.stringify(collectionUploadedUrl.value),
    status: '2'
  }
  billApi.update(params).then(res => {
    proxy.$modal.msgSuccess('收款成功!')
    collectionVisible.value = false
    getList()
  })
}

// 表格多选
function handleSelectionChange(val) {
  multipleSelection.value = val
}

function getList() {
  loading.value = true
  let params = {
    roomId: checkInInfo.value.roomId,
    ...queryParams.value,
    status: '1'
  }
  billApi.getList(params).then(res => {
    billList.value = res.data.rows
    total.value = res.data.total
    amountTotalInfo.value = res.data
  }).finally(() => {
    loading.value = false
  })
}

onMounted(() => {
  getList()
})
</script>